package niuKe;

import java.util.ArrayDeque;
import java.util.Deque;

public class BM1链表反转 {

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        ReverseList(head);
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    public static ListNode ReverseList(ListNode head) {
        if (head.next == null) return head;
        ListNode pre = head;
        ListNode cur = head.next;
        head.next = null;
        ListNode tmp = null;
        while(cur != null) {
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return cur;
    }

    public static ListNode ReverseList_1(ListNode head) {
        Deque<Integer> stack = new ArrayDeque<Integer>();
        ListNode cur = head;
        while (cur != null) {
            stack.addLast(cur.val);
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            cur.val = stack.removeLast();
            cur = cur.next;
        }
        return head;
    }
}
